package handler

import (
	"context"
	"encoding/json"
	"log"
	"math/rand"
	"srv-server/basic/global"
	"srv-server/internal/dao"
	"srv-server/internal/model"
	__ "srv-server/proto"
	"time"
)

type RunServer struct {
	__.UnimplementedRunServerServer
}

func (s *RunServer) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {

	code := rand.Intn(9000) + 1000

	//sms, _ := pkg.SendSms(in.Phone, strconv.Itoa(code))
	//
	//if *sms.Body.Code != "OK" {
	//	panic("第三方失败")
	//}

	global.Rds.Set(context.Background(), "sendsms"+in.Phone+in.Course, code, time.Hour*5)

	return &__.SendSmsResp{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *RunServer) LoginUser(_ context.Context, in *__.LoginUserReq) (*__.LoginUserResp, error) {

	var user model.User
	dao.GetOneId(&model.User{
		Phone: in.Phone,
	}, &user)

	if user.Id == 0 {

		dao.Create(&model.User{
			Name:   in.Name,
			Phone:  in.Phone,
			Status: 1,
		})
	}

	dao.GetOneId(&model.User{
		Phone: in.Phone,
	}, &user)

	get, _ := global.Rds.Get(context.Background(), "sendsms"+in.Phone+"login").Int()

	if in.Sendsmscode != int64(get) {
		return &__.LoginUserResp{
			Message: "验证码不正确",
			Code:    402,
		}, nil
	}

	return &__.LoginUserResp{
		Message: "登录成功",
		Code:    200,
	}, nil
}

func (s *RunServer) SubList(_ context.Context, in *__.SubListReq) (*__.SubListResp, error) {

	var sub []model.Subject
	var lists []*__.SubList

	global.DB.Find(&sub)
	for _, v := range sub {

		lists = append(lists, &__.SubList{
			Id:     int64(v.Id),
			Image:  v.Image,
			Name:   v.Name,
			Info:   v.Info,
			Status: int64(v.Status),
			Likes:  int64(v.Likes),
		})

	}

	marshal, _ := json.Marshal(&lists)

	global.Rds.Set(context.Background(), "sublist", marshal, time.Hour*5)

	return &__.SubListResp{
		List: lists,
	}, nil
}

func (s *RunServer) RecommendList(_ context.Context, in *__.RecommendListReq) (*__.RecommendListResp, error) {

	var sub []model.Subject
	var lists []*__.SubList
	var count int64

	if in.Recommend == 1 {
		global.DB.Where("status = 1").Find(&sub).Count(&count)

		log.Println(count)
		if count > 10 {
			return &__.RecommendListResp{}, nil
		}

		for _, v := range sub {

			lists = append(lists, &__.SubList{
				Id:     int64(v.Id),
				Image:  v.Image,
				Name:   v.Name,
				Info:   v.Info,
				Status: int64(v.Status),
				Likes:  int64(v.Likes),
			})

		}

		marshal, _ := json.Marshal(&lists)

		global.Rds.Set(context.Background(), "sublist", marshal, time.Hour*5)
	} else {
		global.DB.Order("likes desc").Find(&sub)

		for _, v := range sub {

			lists = append(lists, &__.SubList{
				Id:     int64(v.Id),
				Image:  v.Image,
				Name:   v.Name,
				Info:   v.Info,
				Status: int64(v.Status),
				Likes:  int64(v.Likes),
			})

		}
		marshal, _ := json.Marshal(&lists)

		global.Rds.Set(context.Background(), "sublistlikes", marshal, time.Hour*5)

	}

	return &__.RecommendListResp{
		List: lists,
	}, nil
}
